﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using APMS.WebSite.Models;
using System.Data.OracleClient;
using APMS.WebSite.Models.DataStore;
using APMS.WebSite.Common;

namespace APMS.WebSite.Controllers
{
    [HandleError]
    public class ProjectUserController : BaseController
    {
        #region Keys for ViewData
        /// <summary>
        /// Use in method List
        /// </summary>
        public const string PROJECTS_FOR_USER = "ProjectsForUser";

        /// <summary>
        /// Use in method OverView
        /// </summary>
        public const string CURRENT_PROJECT = "currentProject";
        #endregion

        /// <summary>
        /// Default action
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View("List");
        }
        
        /// <summary>
        /// Display the Project Dashboard for given projectId
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult ListUser(int projectId)
        {
            // TODO: Move to ProjectService
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from projectUser in db.ProjectUser
                where projectUser.ProjectID == projectId
                select projectUser;

            if (query.Count() > 0)
            {
                //foreach (Project project in ViewData[ProjectController.PROJECTS_FOR_USER] as List<Project>)
                //Project currentProject = query.First();
                //ViewData[CURRENT_PROJECT] = currentProject;
                //ViewData[Constants.ViewData.TITLE] = 
                //String.Format("Agile Project Management System - {0}", currentProject.ProjectName);
                //ViewData["ProjectName"] = currentProject.ProjectName;
            }
            else
            {
                throw new ArgumentException("No projectID specify");
            }

            #region Old code
            ////// Test binding with LINQ - Oracle
            ////var query =
            ////    from p in database.Project 
            ////    where p.ProjectID == Convert.ToString(id)
            ////    select p;

            ////List<Project> projects = query.ToList();
            ////Project currentProject = projects[0];
            //////Project currentProject = query as Project;
            
            //////Project currentProject = dataContext.Project.First(p => p.ProjectID == "1");

            //var query = from p in database.Project select p;
            //List<Project> projects = query.ToList();
            //Project currentProject = projects[0];

            //// use First() in place of Where() to find the first or only one 
            ////Project currentProject = database.Project.First(p => p.ProjectID == Convert.ToString(id));
            
            //// TODO: Read from constants AND ProjectDto.Name
            //ViewData["Title"] = String.Format("Agile Project Management System - {0}", currentProject.ProjectName);
            //// TODO: Read from ProjectDto.Name
            //ViewData["ProjectName"] = currentProject.ProjectName;
            #endregion

            return View("test");
        }

        [Obsolete("Use UserController.AddUserProject()")]
        public ActionResult AddUser(int projectId, String UserName)
        {
            UserName = Request.QueryString["UserName"];
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            //throw new NotImplementedException();  
            //Is project avalible
            var querys =
                from project in db.Project
                where
                    project.ProjectID == projectId
                select project;
            //Is this user avalible in this project
            var querys1 =
                from projectUser in db.ProjectUser
                where
                    projectUser.UserName == UserName &&
                    projectUser.ProjectID == projectId
                select projectUser;
            //Is this user avalible in system
            var querys2 =
                from user in db.Users
                where
                    user.UserName == UserName
                select user;
            if (querys.Count() > 0 && querys2.Count() > 0 && querys1.Count() <= 0)
            {
                // new project
                Project currentProject = querys.First();

                ProjectUser newProjectUser = new ProjectUser();
                newProjectUser.ProjectID = projectId;
                newProjectUser.JoinDate = DateTime.Now;
                newProjectUser.UserName = UserName;

                db.ProjectUser.Add(newProjectUser);
                db.SubmitChanges();
                //ViewData["justwanttopreviewmassage"] = newProject.ToString() + newProjectUser.ToString();
            }
            else {
                //ViewData["justwanttopreviewmassage"] = "No data";
            }

            // TODO: Add this line back
            return ListUser(projectId);
        }

        private void deleteProject(int projectId)
        {
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from projectUser in db.ProjectUser
                where
                    projectUser.ProjectID == projectId 
                select projectUser;

            if (query.Count() <= 0)
            {
                try
                {
                    Project deleteproject = db.Project.Single(p => p.ProjectID == projectId);
                    db.Project.Remove(deleteproject);
                    db.SubmitChanges();
                }
                catch (InvalidOperationException ex)
                {
                    System.Console.WriteLine("called on set with zero items");
                }
            }
        }

        [Obsolete("Use UserController.RemoveUserProject()")]
        public ActionResult leave(int projectId, String UserName)
        {
            // TODO: Move to ProjectService
            UserName = Request.QueryString["UserName"];
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from projectUser in db.ProjectUser
                where
                    projectUser.ProjectID == projectId &&
                    projectUser.UserName == UserName
                select projectUser;

            if (query.Count() > 0)
            {
                try
                {
                    //ProjectUser deleteuser = query.First();
                    //db.ProjectUser.DeleteAllOnSubmit(query);
                    db.ProjectUser.RemoveAll(query);
                    db.SubmitChanges();
                    deleteProject(projectId);
                }
                catch (InvalidOperationException ex)
                {
                    System.Console.WriteLine("called on set with zero items");
                }
            }
            else
            {
                throw new ArgumentException("No projectID specify");
            }

            #region Old code
            ////// Test binding with LINQ - Oracle
            ////var query =
            ////    from p in database.Project 
            ////    where p.ProjectID == Convert.ToString(id)
            ////    select p;

            ////List<Project> projects = query.ToList();
            ////Project currentProject = projects[0];
            //////Project currentProject = query as Project;

            //////Project currentProject = dataContext.Project.First(p => p.ProjectID == "1");

            //var query = from p in database.Project select p;
            //List<Project> projects = query.ToList();
            //Project currentProject = projects[0];

            //// use First() in place of Where() to find the first or only one 
            ////Project currentProject = database.Project.First(p => p.ProjectID == Convert.ToString(id));

            //// TODO: Read from constants AND ProjectDto.Name
            //ViewData["Title"] = String.Format("Agile Project Management System - {0}", currentProject.ProjectName);
            //// TODO: Read from ProjectDto.Name
            //ViewData["ProjectName"] = currentProject.ProjectName;
            #endregion

            return ListUser(projectId);
        }


    }
}
